const myTools = {}

// Session
myTools.saveSession = function (key, data) {
    const dataJSON = JSON.stringify(data)
    window.sessionStorage.setItem(key, dataJSON)
}

myTools.getSession = function (key, type) {
    const dataJSON = window.sessionStorage.getItem(key)
    return type === 1 ? dataJSON : JSON.parse(dataJSON)
}

myTools.removeSession = function (key) {
    window.sessionStorage.removeItem(key)
}

myTools.pushSession = function (key, data) {
    const session = window.sessionStorage
    if (!session.getItem(key)) {
        const Arr = [data]
        myTools.saveSession(key, Arr)
    } else {
        const Arr = myTools.getSession(key)
        Arr.push(data)
        myTools.saveSession(key, Arr)
    }
}

// Array

myTools.arrSome = function (list, x) {
    // 如果x存在于list中，返回x在list中的位置，否则返回false
    let index
    if (typeof x !== 'object') {
        const isSaved = list.some(function (item, idx, array) {
            index = idx
            return item === x
        })
        return isSaved === true ? index : false
    } else {
        const isSaved = list.some(function (item, idx, array) {
            index = idx
            return JSON.stringify(item) === JSON.stringify(x)
        })
        return isSaved === true ? index : false
    }
}
myTools.arrSomeItem = function (arr, key, x) {
  // 针对数组中元素全是结构相同obj，对obj中的某个key进行对比，如果存在则返回索引值
  let idx
  let isHave = arr.some((item, i) => {
    idx = i
    return item[key] === x
  })
  return isHave === true ? idx : false
}

myTools.arrUnique = function(arr) {
	let temp = []
	for(let i = 0; i<arr.length; i++) {
		for(let j = i+1; j<arr.length; j++){
			if(arr[i] === arr[j]){
				i++;
				j=i
			}
		}
		temp.push(arr[i])
	}
	return temp
}

// History
myTools.historyTo = function (a, b) {
    if (b === null) {
        if (a === null || a === 0) {
            window.location.reload()
        } else {
           window.history.go(a)
        }
    } else if (a === -1) {
        window.history.back()
    } else {
        window.history.forward()
    }
}

// String
myTools.subStr_b = function(str, startStr, endStr, x){
	// x: 0->(),  1->[],  2-> [), 3->(]
	let pos_s, pos_e, pos_start, pos_end
	pos_s = str.indexOf(startStr)
	pos_e = str.indexOf(endStr)

	switch(x) {
		case 0:
			pos_start = pos_s + startStr.length
			pos_end = pos_e
			break
		case 1:
			pos_start = pos_s
			pos_end = pos_e + endStr.length
			break
		case 2:
			pos_start = pos_s
			pos_end = pos_e
			break
		case 3:
			pos_start = pos_s + startStr.length
			pos_end = pos_e + endStr.length
			break
	}

	return str.slice(pos_start, pos_end)
}



myTools.getWindowSize = function(x) {
  let Y = document.documentElement.clientHeight || document.body.clientHeight
  let X = document.documentElement.clientWidth || document.body.clientWidth
  switch(x) {
    case 0: return X
    case 1: return Y
    default: return {
      width: X,
      height: Y
    }
  }
}
myTools.getScrollHeight = function() {
  return document.documentElement.scrollHeight||document.body.scrollHeight;
}
myTools.getScrollTop = function() {
  return document.documentElement.scrollTop||document.body.scrollTop;
}
myTools.isToBottom = function() {
  let winY = this.getWindowSize(1)
  let scrollH = this.getScrollHeight()
  let scrollY = this.getScrollTop()
  return winY + scrollY === scrollH
}

myTools.axiosPost = async function (vm, url, params) {
  let {status, data} = await vm.$axios.post(url, { params })
  if (status === 200) {
    return data
  } else {
    console.log(`jsTools axiosPost status: ${status}, url: ${url}`)
  }
}


// https://segmentfault.com/a/1190000018445196
myTools.debounce = function(fn, t) {
  let timer
  return function () {
    let args = arguments
    clearTimeout(timer)
    timer = setTimeout(function() {
      fn.apply(this, args)
    }, t)
  }
}
myTools.throttle = function(fn, x, y, t) {
  var timer
  return function () {
    if(timer) { return }
    timer = setTimeout(function(){
      fn(x,y)
      clearInterval(timer)
    }, t)
  }
}

myTools.powerset = function(arr){
  let ps = [[]]
  for(let i = 0; i < arr.length; i++){
    for(let j = 0, len = ps.length; j<len; j++){  // 注意 len=ps.length前用的是逗号","
      ps.push(ps[j].concat(arr[i]))
    }
  }
  return ps
}

myTools.checkFloat = function(n, x) {
  let str = n.toString()
  let idx = str.indexOf('.')
  if(x > 0) {
    if(idx === -1){
      let appendStr = Math.pow(10, x).toString().slice(1)
      return str + "." + appendStr
    }else{
      let tailCount = str.length - idx -1
      if(x>tailCount){
        let appendStr = Math.pow(10, (x-tailCount)).toString().slice(1)
        return str + appendStr
      }else{
        return str.substr(0, (idx+x+1))
      }
    }
  }else if(x === 0) {
    if(idx === -1){
      return str
    }else{
      return str.substr(0, idx)
    }
  }
}

export {
    myTools
}
